package cn.easyutil.deploy.util;

import java.io.*;
import java.nio.charset.Charset;

/**
 * 文件操作工具类
 * 
 * @author spc
 *
 */
public class FileUtil {


	/**
	 * 文件转byte
	 * 
	 * @param filePath
	 * @return
	 */
	public static byte[] toByteArray(String filePath) {
		File file = new File(filePath);
		return toByteArray(file);
	}

	/**
	 * 文件读取流
	 * 
	 * @param filePath
	 * @return
	 */
	public static InputStream toInput(String filePath) {
		try {
			return new FileInputStream(new File(filePath));
		} catch (FileNotFoundException e) {
			throw new RuntimeException(e);
		}
	}

	/**
	 * 保存文件到本地
	 * 
	 * @param in
	 */
	public static void save(InputStream in, File file) {
		FileOutputStream out = null;
		try {
			out = new FileOutputStream(file);
			out.write(IOUtil.inputToByte(in));
			out.flush();
		} catch (IOException e) {
		} finally {
			if (out != null) {
				try {
					out.close();
				} catch (IOException e) {
					throw new RuntimeException(e);
				}
			}
		}
	}

	/**
	 * 文件转byte
	 * 
	 * @param file
	 * @return
	 */
	public static byte[] toByteArray(File file) {
		FileInputStream fin = null;
		ByteArrayOutputStream out = null;
		try {
			out = new ByteArrayOutputStream();
			fin = new FileInputStream(file);
			byte[] but = new byte[1024 * 1024];
			int length = 0;
			while ((length = fin.read(but)) != -1) {
				out.write(but, 0, length);
			}
			return out.toByteArray();
		} catch (Exception e) {
			throw new RuntimeException(e);
		} finally {
			try {
				fin.close();
				out.close();
			} catch (IOException e) {
				throw new RuntimeException(e);
			}
		}
	}

	/**
	 * 将文件头转换成16进制字符串
	 * 
	 * @return 16进制字符串
	 */
	private static String bytesToHexString(byte[] src) {

		StringBuilder stringBuilder = new StringBuilder();
		if (src == null || src.length <= 0) {
			return null;
		}
		for (int i = 0; i < src.length; i++) {
			int v = src[i] & 0xFF;
			String hv = Integer.toHexString(v);
			if (hv.length() < 2) {
				stringBuilder.append(0);
			}
			stringBuilder.append(hv);
		}
		return stringBuilder.toString();
	}

	public static String read(File file, Charset charset){
		byte[] bytes = toByteArray(file);
		return new String(bytes,charset);
	}

}
